package cn.harry.modular.achievement.service.impl;

import cn.harry.modular.achievement.AchievementAuditVO;
import cn.harry.modular.achievement.domain.*;
import cn.harry.modular.achievement.enums.AchievementStateEnums;
import cn.harry.modular.achievement.enums.AchievementTypeEnums;
import cn.harry.modular.achievement.enums.NoticeTypeEnums;
import cn.harry.modular.achievement.mapper.AchievementMapper;
import cn.harry.modular.achievement.service.*;
import cn.harry.modular.achievement.vo.EchartsOptionVO;
import cn.harry.modular.achievement.vo.TeacherAchievementVO;
import cn.harry.modular.system.domain.SysDictData;
import cn.harry.modular.system.domain.SysUser;
import cn.harry.modular.system.service.SysDictDataService;
import cn.harry.modular.system.service.SysUserService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 成果资源服务实现类
 *
 * @author harry
 * @公众号 Harry技术
 */
@Service
@RequiredArgsConstructor
public class AchievementServiceImpl extends ServiceImpl<AchievementMapper, Achievement> implements AchievementService {

    private final NoticeService noticeService;
    private final SysDictDataService sysDictDataService;
    private final SysUserService sysUserService;

    private final AchievementAcademicPapersService achievementAcademicPapersService;
    private final AchievementCourseTeachingService achievementCourseTeachingService;
    private final AchievementPatentApplicationService achievementPatentApplicationService;
    private final AchievementResearchProjectsService achievementResearchProjectsService;
    private final AchievementTeachingRewardsService achievementTeachingRewardsService;

    @Override
    public boolean audit(AchievementAuditVO vo) {
        String state = vo.getState();
        Achievement achievement = getById(vo.getId());
        achievement.setState(state);

        Long userId = achievement.getUploader();
        String title = achievement.getTitle();

        String content = StrUtil.format("您的成果资源【{}】已被审核，审核结果为：{}", title, AchievementStateEnums.getDescByCode(state));
        noticeService.saveInfo(userId, content, NoticeTypeEnums.AUDIT_FEEDBACK);

        return updateById(achievement);
    }

    @Override
    public EchartsOptionVO myAchievement(long userId) {
        EchartsOptionVO vo = new EchartsOptionVO();
        List<SysDictData> dictDataList = sysDictDataService.lambdaQuery().eq(SysDictData::getDictType, "achievement_type").eq(SysDictData::getStatus, "1").orderByAsc(SysDictData::getDictSort).list();

        // 根据成果类型分组
        JSONArray x = new JSONArray();
        JSONArray y = new JSONArray();
        for (SysDictData sysDictData : dictDataList) {
            x.put(sysDictData.getDictLabel());
            String type = sysDictData.getDictValue();
            // 1	课程教学
            if (AchievementTypeEnums.COURSE_TEACHING.getCode().equals(type)) {
                long count = achievementCourseTeachingService.count(Wrappers.<AchievementCourseTeaching>lambdaQuery().eq(AchievementCourseTeaching::getUserId, userId));
                y.put(count);
            }
            // 2	学术论文
            if (AchievementTypeEnums.ACADEMIC_PAPER.getCode().equals(type)) {
                long count = achievementAcademicPapersService.count(Wrappers.<AchievementAcademicPapers>lambdaQuery().eq(AchievementAcademicPapers::getUserId, userId));
                y.put(count);
            }
            // 3	科研项目
            if (AchievementTypeEnums.RESEARCH_PROJECT.getCode().equals(type)) {
                long count = achievementResearchProjectsService.count(Wrappers.<AchievementResearchProjects>lambdaQuery().eq(AchievementResearchProjects::getUserId, userId));
                y.put(count);
            }
            //   4	教学奖励
            if (AchievementTypeEnums.TEACHING_AWARD.getCode().equals(type)) {
                long count = achievementTeachingRewardsService.count(Wrappers.<AchievementTeachingRewards>lambdaQuery().eq(AchievementTeachingRewards::getUserId, userId));
                y.put(count);
            }
            // 5	专利申请
            if (AchievementTypeEnums.PATENT_APPLICATION.getCode().equals(type)) {
                long count = achievementPatentApplicationService.count(Wrappers.<AchievementPatentApplication>lambdaQuery().eq(AchievementPatentApplication::getUserId, userId));
                y.put(count);
            }
            vo.setXData(x);
            vo.setYData(y);
        }
        return vo;
    }

    @Override
    public EchartsOptionVO typeAchievement() {
        EchartsOptionVO vo = new EchartsOptionVO();
        List<SysDictData> dictDataList = sysDictDataService.lambdaQuery().eq(SysDictData::getDictType, "achievement_type").eq(SysDictData::getStatus, "1").orderByAsc(SysDictData::getDictSort).list();

        // 根据成果类型分组
        JSONArray x = new JSONArray();
        JSONArray y = new JSONArray();
        for (SysDictData sysDictData : dictDataList) {
            x.put(sysDictData.getDictLabel());
            String type = sysDictData.getDictValue();

            // 1	课程教学
            if (AchievementTypeEnums.COURSE_TEACHING.getCode().equals(type)) {
                long count = achievementCourseTeachingService.count();
                y.put(count);
            }
            // 2	学术论文
            if (AchievementTypeEnums.ACADEMIC_PAPER.getCode().equals(type)) {
                long count = achievementAcademicPapersService.count();
                y.put(count);
            }
            // 3	科研项目
            if (AchievementTypeEnums.RESEARCH_PROJECT.getCode().equals(type)) {
                long count = achievementResearchProjectsService.count();
                y.put(count);
            }
            //   4	教学奖励
            if (AchievementTypeEnums.TEACHING_AWARD.getCode().equals(type)) {
                long count = achievementTeachingRewardsService.count();
                y.put(count);
            }
            // 5	专利申请
            if (AchievementTypeEnums.PATENT_APPLICATION.getCode().equals(type)) {
                long count = achievementPatentApplicationService.count();
                y.put(count);
            }
            vo.setXData(x);
            vo.setYData(y);
        }
        return vo;
    }

    @Override
    public EchartsOptionVO downloadTop5Achievement() {
        EchartsOptionVO vo = new EchartsOptionVO();

        JSONArray x = new JSONArray();
        JSONArray y = new JSONArray();
        List<SysDictData> dictDataList = sysDictDataService.lambdaQuery().eq(SysDictData::getDictType, "achievement_type").eq(SysDictData::getStatus, "1").orderByAsc(SysDictData::getDictSort).list();
        for (SysDictData sysDictData : dictDataList) {
            String type = sysDictData.getDictValue();

            // 1	课程教学
            if (AchievementTypeEnums.COURSE_TEACHING.getCode().equals(type)) {
                AchievementCourseTeaching item = achievementCourseTeachingService.getOne(Wrappers.<AchievementCourseTeaching>lambdaQuery().orderByDesc(AchievementCourseTeaching::getDownloadCount).last("limit 1"));
               if (item == null){
                   continue;
               }
                y.put(item.getDownloadCount());
                x.put(item.getCourseName());
            }
            // 2	学术论文
            if (AchievementTypeEnums.ACADEMIC_PAPER.getCode().equals(type)) {
                AchievementAcademicPapers item = achievementAcademicPapersService.getOne(Wrappers.<AchievementAcademicPapers>lambdaQuery().orderByDesc(AchievementAcademicPapers::getDownloadCount).last("limit 1"));
                if (item == null){
                    continue;
                }
                x.put(item.getPaperTitle());
                y.put(item.getDownloadCount());
            }
            // 3	科研项目
            if (AchievementTypeEnums.RESEARCH_PROJECT.getCode().equals(type)) {

                AchievementResearchProjects item = achievementResearchProjectsService.getOne(Wrappers.<AchievementResearchProjects>lambdaQuery().orderByDesc(AchievementResearchProjects::getDownloadCount).last("limit 1"));
                if (item == null){
                    continue;
                }
                x.put(item.getProjectName());
                y.put(item.getDownloadCount());
            }
            //   4	教学奖励
            if (AchievementTypeEnums.TEACHING_AWARD.getCode().equals(type)) {
                AchievementTeachingRewards item = achievementTeachingRewardsService.getOne(Wrappers.<AchievementTeachingRewards>lambdaQuery().orderByDesc(AchievementTeachingRewards::getDownloadCount).last("limit 1"));
                if (item == null){
                    continue;
                }
                x.put(item.getRewardName());
                y.put(item.getDownloadCount());
            }
            // 5	专利申请
            if (AchievementTypeEnums.PATENT_APPLICATION.getCode().equals(type)) {
                AchievementPatentApplication item = achievementPatentApplicationService.getOne(Wrappers.<AchievementPatentApplication>lambdaQuery().orderByDesc(AchievementPatentApplication::getDownloadCount).last("limit 1"));
                if (item == null){
                    continue;
                }
                y.put(item.getDownloadCount());
                x.put(item.getPatentTitle());
            }
            vo.setXData(x);
            vo.setYData(y);
        }
        return vo;
    }

    @Override
    public List<Map<String, Object>> teacherAchievement() {
        List<Map<String, Object>> vo = new ArrayList<>();
        List<TeacherAchievementVO> list = this.baseMapper.teacherAchievement();
        Map<Long, List<TeacherAchievementVO>> map = list.stream().filter(item -> item.getUserId() != null).collect(Collectors.groupingBy(TeacherAchievementVO::getUserId));
        for (Map.Entry<Long, List<TeacherAchievementVO>> entry : map.entrySet()) {
            Map<String, Object> map1 = new HashMap<>();
            SysUser user = sysUserService.getById(entry.getKey());
            map1.put("name", user.getUsername());

            List<TeacherAchievementVO> list1 = entry.getValue();
            Integer cnt = list1.stream().map(TeacherAchievementVO::getCnt).reduce(0, Integer::sum);
            map1.put("value", cnt);

            vo.add(map1);
        }
        return vo;
    }
}
